package com.wxzl.community.common.widget;

import android.content.Context;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.bigkoo.pickerview.configure.PickerOptions;
import com.bigkoo.pickerview.listener.ISelectTimeCallback;
import com.bigkoo.pickerview.view.WheelTime;
import com.wxzl.community.common.R;
import com.wxzl.community.common.utils.ext.DateExtKt;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

//范围
public class DateRangeBottomFragment extends BottomSheetFragBase {
    PickerOptions mPickerOptions;
    WheelTime wheelTime;
    boolean isEnd = false;
    private RadioButton rbStart;
    private RadioButton rbEnd;

    public DateRangeBottomFragment(PickerOptions pickerOptions) {
        mPickerOptions = pickerOptions;
        viewInit(pickerOptions.context);
    }

    private void viewInit(Context context) {
    }

    @Override
    public int getLayoutResId() {
        return R.layout.bottom_date_picker;
    }


    /**
     * 初始化View和设置数据等操作的方法
     */
    @Override
    public void initView() {
        Button btnOk = rootView.findViewById(R.id.btnOk);
        Button btnCancel = rootView.findViewById(R.id.btnCancel);
        rbStart = rootView.findViewById(R.id.rb_select_start_time);
        rbEnd = rootView.findViewById(R.id.rb_select_end_time);

        rbStart.setOnCheckedChangeListener((buttonView, isChecked) -> isEnd = !isChecked);

        btnOk.setOnClickListener(v -> {
            if (start == null || end == null) {
                Toast.makeText(getActivity(), "请选择时间", Toast.LENGTH_SHORT).show();
                return;
            }
            if (start.getTime() > end.getTime()) {
                Toast.makeText(getActivity(), "时间范围有误", Toast.LENGTH_SHORT).show();
                return;
            }
            if (onDateSelectedListener != null) {
                if (start != null && end != null) onDateSelectedListener.onSelected(start, end);
            }
            dismiss();
        });
        btnCancel.setOnClickListener(v -> dismiss());
        // 时间转轮 自定义控件
        LinearLayout timePickerView = (LinearLayout) rootView.findViewById(R.id.timepicker);
        timePickerView.setBackgroundColor(mPickerOptions.bgColorWheel);
        initWheelTime(timePickerView);


    }


    public void setOnDateSelectedListener(OnDateSelectedListener onDateSelectedListener) {
        this.onDateSelectedListener = onDateSelectedListener;
    }

 private    OnDateSelectedListener onDateSelectedListener;

    public interface OnDateSelectedListener {
        void onSelected(Date startDate, Date endDate);

    }

    Date start, end;

    private void initWheelTime(LinearLayout timePickerView) {
        wheelTime = new WheelTime(timePickerView, mPickerOptions.type, mPickerOptions.textGravity, mPickerOptions.textSizeContent);

        wheelTime.setSelectChangeCallback(new ISelectTimeCallback() {
            @Override
            public void onTimeSelectChanged() {
                try {
                    Date date = WheelTime.dateFormat.parse(wheelTime.getTime());
                    if (isEnd) {
                        end = date;
                        rbEnd.setText(DateExtKt.yyyyMMdd(end));
                    } else {
                        start = date;
                        rbStart.setChecked(true);
                        rbStart.setText(DateExtKt.yyyyMMdd(start));
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });


        wheelTime.setLunarMode(mPickerOptions.isLunarCalendar);

        if (mPickerOptions.startYear != 0 && mPickerOptions.endYear != 0
                && mPickerOptions.startYear <= mPickerOptions.endYear) {
            setRange();
        }

        //若手动设置了时间范围限制
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            if (mPickerOptions.startDate.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                throw new IllegalArgumentException("startDate can't be later than endDate");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.startDate != null) {
            if (mPickerOptions.startDate.get(Calendar.YEAR) < 1900) {
                throw new IllegalArgumentException("The startDate can not as early as 1900");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.endDate != null) {
            if (mPickerOptions.endDate.get(Calendar.YEAR) > 2100) {
                throw new IllegalArgumentException("The endDate should not be later than 2100");
            } else {
                setRangDate();
            }
        } else {//没有设置时间范围限制，则会使用默认范围。
            setRangDate();
        }

        setTime();
        wheelTime.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day
                , mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds);
        wheelTime.setTextXOffset(mPickerOptions.x_offset_year, mPickerOptions.x_offset_month, mPickerOptions.x_offset_day,
                mPickerOptions.x_offset_hours, mPickerOptions.x_offset_minutes, mPickerOptions.x_offset_seconds);
        wheelTime.setItemsVisible(mPickerOptions.itemsVisibleCount);
        wheelTime.setAlphaGradient(mPickerOptions.isAlphaGradient);

        wheelTime.setCyclic(mPickerOptions.cyclic);
        wheelTime.setDividerColor(mPickerOptions.dividerColor);
        wheelTime.setDividerType(mPickerOptions.dividerType);
        wheelTime.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier);
        wheelTime.setTextColorOut(mPickerOptions.textColorOut);
        wheelTime.setTextColorCenter(mPickerOptions.textColorCenter);
        wheelTime.isCenterLabel(mPickerOptions.isCenterLabel);
    }

    /**
     * 设置默认时间
     */
    public void setDate(Calendar date) {
        mPickerOptions.date = date;
        setTime();
    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRange() {
        wheelTime.setStartYear(mPickerOptions.startYear);
        wheelTime.setEndYear(mPickerOptions.endYear);

    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRangDate() {
        wheelTime.setRangDate(mPickerOptions.startDate, mPickerOptions.endDate);
        initDefaultSelectedDate();
    }

    private void initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (mPickerOptions.date == null || mPickerOptions.date.getTimeInMillis() < mPickerOptions.startDate.getTimeInMillis()
                    || mPickerOptions.date.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                mPickerOptions.date = mPickerOptions.startDate;
            }
        } else if (mPickerOptions.startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            mPickerOptions.date = mPickerOptions.startDate;
        } else if (mPickerOptions.endDate != null) {
            mPickerOptions.date = mPickerOptions.endDate;
        }
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private void setTime() {
        int year, month, day;
        Calendar calendar = Calendar.getInstance();

        if (mPickerOptions.date == null) {
            calendar.setTimeInMillis(System.currentTimeMillis());
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);

        } else {
            year = mPickerOptions.date.get(Calendar.YEAR);
            month = mPickerOptions.date.get(Calendar.MONTH);
            day = mPickerOptions.date.get(Calendar.DAY_OF_MONTH);

        }

        wheelTime.setPicker(year, month, day);
    }

}
